//
//  KQConversationCell.swift
//  JChat
//
//  Created by JIGUANG on 2017/3/22.
//  Copyright © 2017年 HXHG. All rights reserved.
//

import UIKit
import KQChatSDK

open class KQConversationCell: UITableViewCell {
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        _init()
    }
    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        _init()
    }
    
    open override func awakeFromNib() {
        super.awakeFromNib()
        _init()
    }
    
    private lazy var line: UILabel = UILabel()

    private lazy var avatorView: UIImageView = {
        let avatorView = UIImageView()
        avatorView.contentMode = .scaleToFill
        return avatorView
    }()
    private lazy var statueView: UIImageView = UIImageView()
    private lazy var titleLabel: UILabel = {
        let titleLabel = UILabel()
        titleLabel.font = UIFont(name: KQCHAT_FONT_NAME, size: 16)
        return titleLabel
    }()
    private lazy var msgLabel: UILabel = {
        let msgLabel = UILabel()
        msgLabel.textColor = UIColor(netHex: 0x808080)
        msgLabel.font = UIFont(name: KQCHAT_FONT_NAME, size: 14)
        return msgLabel
    }()
    private lazy var dateLabel: UILabel = {
        let dateLabel = UILabel()
        dateLabel.textAlignment = .right
        dateLabel.font = UIFont(name: KQCHAT_FONT_NAME, size: 12)
        dateLabel.textColor = UIColor(netHex: 0xB3B3B3)
        return dateLabel
    }()
    private lazy var redPoin: UILabel = {
        let redPoin = UILabel(frame: CGRect(x: 55 - 10, y: 4, width: 20, height: 20))
        redPoin.textAlignment = .center
        redPoin.font = UIFont(name: KQCHAT_FONT_NAME, size: 11)
        redPoin.textColor = .white
        redPoin.layer.backgroundColor = UIColor(netHex: 0xEB424C).cgColor
        redPoin.textAlignment = .center
        return redPoin
    }()
    
    //MARK: - public func
    
    open func bindSearchConversation(_ conversation: WFCCConversationSearchInfo) {
        guard let observationInfo = WFCCIMService.sharedWFCIM().getConversationInfo(conversation.conversation) else { return
        }
        self.bindConversation(observationInfo)
    }
    open func bindConversation(_ conversation: WFCCConversationInfo) {
        statueView.isHidden = true
        let isGroup = conversation.conversation.type
        if conversation.unreadCount != nil && conversation.unreadCount.unread > 0 {
            redPoin.isHidden = false
            var text = ""
            if conversation.unreadCount.unread > 99 {
                text = "99+"
                redPoin.layer.cornerRadius = 10.0
                redPoin.layer.masksToBounds = true
                redPoin.frame = CGRect(x: 55 - 16.5, y: 4, width: 33, height: 20)
            } else {
                redPoin.layer.cornerRadius = 10.0
                redPoin.layer.masksToBounds = true
                redPoin.frame = CGRect(x: 55 - 10, y: 4, width: 20, height: 20)
                text = "\(conversation.unreadCount!.unread)"
            }
            redPoin.text = text
            
            var isNoDisturb = false
            if isGroup == .Group_Type {
                if conversation.conversation.target != nil  {
                    isNoDisturb = conversation.isSilent
                }
            } else {
                if let _ = conversation.conversation.target {
                    isNoDisturb = conversation.isSilent
                }
            }
            
            if isNoDisturb {
                redPoin.layer.cornerRadius = 4.0
                redPoin.layer.masksToBounds = true
                redPoin.text = ""
                redPoin.frame = CGRect(x: 55 - 4, y: 8, width: 8, height: 8)
            }
        } else {
            redPoin.isHidden = true
        }
        
        if let latestMessage = conversation.lastMessage {
            let time = conversation.timestamp / 1000
            let date = Date(timeIntervalSince1970: TimeInterval(time))
            dateLabel.text = date.conversationDate()
            msgLabel.text = latestMessage.digest()
            
        } else {
            dateLabel.text = ""
        }

        
        

        if let draft = conversation.draft {
            if !draft.isEmpty {
                msgLabel.attributedText = getAttributString(attributString: "[草稿] ", string: draft)
            }
        }
        
        
        var userInfo = WFCCIMService.sharedWFCIM().getUserInfo(conversation.conversation.target, refresh: false)
        if userInfo?.userId.count == 0 {
            userInfo = WFCCUserInfo.init()
            userInfo?.userId = conversation.conversation.target
        }
        if (userInfo?.friendAlias.count ?? 0) > 0 {
            titleLabel.text = userInfo?.friendAlias
        } else if (userInfo?.displayName.count ?? 0) > 0 {
            titleLabel.text = userInfo?.displayName
        } else {
            titleLabel.text = "\(conversation.conversation.target ?? "")"
        }
        if userInfo?.portrait == nil {
            
        } else {
            
        }
        
        let url = URL(string: userInfo?.portrait ?? "")
        var image:UIImage?
        if userInfo?.gender == 1 {
            image = self.userDefaultIcon(sex: 1)
        } else {
            image = self.userDefaultIcon(sex: 0)
        }
        self.avatorView.yy_setImage(with: url, placeholder: image)

//
//        if conversation.ex.isSticky {
//            backgroundColor = UIColor(netHex: 0xF5F6F8)
//        } else {
//            backgroundColor = .white
//        }
    }
    
   
    func getAttributString(attributString: String, string: String) -> NSMutableAttributedString {
        let attr = NSMutableAttributedString(string: "")
        var attrSearchString: NSAttributedString!
        attrSearchString = NSAttributedString(string: attributString, attributes: convertToOptionalNSAttributedStringKeyDictionary([ convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor) : UIColor(netHex: 0xEB424C), convertFromNSAttributedStringKey(NSAttributedString.Key.font) : UIFont(name: KQCHAT_FONT_MEDIUM_NAME, size: 14)]))
        attr.append(attrSearchString)
        attr.append(NSAttributedString(string: string))
        return attr
    }
    
    private lazy var groupDefaultIcon = UIImage.loadImage("com_icon_group_50")
    private func userDefaultIcon(sex: Int) -> UIImage {
        if sex == 0 {
            return UIImage.init(named: "kq_chat_header_woman.png")!
        }
        return UIImage.init(named: "kq_chat_header_man.png")!
    }
    //MARK: - private func
    private func _init() {
        avatorView.image = userDefaultIcon(sex: 0)
        statueView.image = UIImage.loadImage("com_icon_shield")
        
        line.backgroundColor = UIColor(netHex: 0xE8E8E8)
        line.layer.backgroundColor = UIColor(netHex: 0xE8E8E8).cgColor
        
        addSubview(line)
        contentView.addSubview(avatorView)
        contentView.addSubview(statueView)
        contentView.addSubview(titleLabel)
        contentView.addSubview(msgLabel)
        contentView.addSubview(dateLabel)
        contentView.addSubview(redPoin)
        
        KQChatUtils.shared().addCorner(on: avatorView, rect: CGRect(x: 0, y: 0, width: 40, height: 40), roundingCorners: .allCorners, cornerRadius: 4)
        
        addConstraint(_JCLayoutConstraintMake(line, .bottom, .equal, contentView, .bottom))
        addConstraint(_JCLayoutConstraintMake(line, .left, .equal, self, .left, 15))
        addConstraint(_JCLayoutConstraintMake(line, .right, .equal, self, .right, -15))
        addConstraint(_JCLayoutConstraintMake(line, .height, .equal, nil, .notAnAttribute, 0.5))
        
        addConstraint(_JCLayoutConstraintMake(avatorView, .left, .equal, contentView, .left, 15))
        addConstraint(_JCLayoutConstraintMake(avatorView, .top, .equal, contentView, .top, 12))
        addConstraint(_JCLayoutConstraintMake(avatorView, .width, .equal, nil, .notAnAttribute, 40))
        addConstraint(_JCLayoutConstraintMake(avatorView, .height, .equal, nil, .notAnAttribute, 40))
        
        addConstraint(_JCLayoutConstraintMake(titleLabel, .left, .equal, avatorView, .right, 10.5))
        addConstraint(_JCLayoutConstraintMake(titleLabel, .top, .equal, contentView, .top, 10.5))
        addConstraint(_JCLayoutConstraintMake(titleLabel, .right, .equal, dateLabel, .left, -3))
        addConstraint(_JCLayoutConstraintMake(titleLabel, .height, .equal, nil, .notAnAttribute, 22.5))
        
        addConstraint(_JCLayoutConstraintMake(msgLabel, .left, .equal, titleLabel, .left))
        addConstraint(_JCLayoutConstraintMake(msgLabel, .top, .equal, titleLabel, .bottom, 1.5))
        addConstraint(_JCLayoutConstraintMake(msgLabel, .right, .equal, statueView, .left, -5))
        addConstraint(_JCLayoutConstraintMake(msgLabel, .height, .equal, nil, .notAnAttribute, 20))
        
        addConstraint(_JCLayoutConstraintMake(dateLabel, .top, .equal, contentView, .top, 16))
        addConstraint(_JCLayoutConstraintMake(dateLabel, .right, .equal, contentView, .right, -15))
        addConstraint(_JCLayoutConstraintMake(dateLabel, .height, .equal, nil, .notAnAttribute, 16.5))
        addConstraint(_JCLayoutConstraintMake(dateLabel, .width, .equal, nil, .notAnAttribute, 100))
        
        addConstraint(_JCLayoutConstraintMake(statueView, .top, .equal, dateLabel, .bottom, 7))
        addConstraint(_JCLayoutConstraintMake(statueView, .right, .equal, contentView, .right, -16))
        addConstraint(_JCLayoutConstraintMake(statueView, .height, .equal, nil, .notAnAttribute, 12))
        addConstraint(_JCLayoutConstraintMake(statueView, .width, .equal, nil, .notAnAttribute, 12))
    }
}

// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? {
	guard let input = input else { return nil }
	return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)})
}

// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String {
	return input.rawValue
}
